#!/usr/bin/env python
# -*- coding:utf-8 -*-
import flask
from flask_restful import Resource, reqparse
from flask import jsonify

from controller.fileController import FileController
from service.fileService import FileService
from utils import commons
from utils.JwtMiddleware import TokenRequire
from utils.response_code import RET
from utils.responseParser import ResponseParser
from utils.myLogging import logger
from werkzeug.exceptions import BadRequest


class FileOtherResource(Resource):

    @classmethod
    def sensitive_update(cls, file_id):
        if not file_id:
            return jsonify(code=RET.NODATA, message='primary key missed', error='primary key missed')

        parser = reqparse.RequestParser()
        parser.add_argument('is_delete', location='form', required=False, help='is_delete参数类型不正确或缺失')
        parser.add_argument('file', location='form', required=True, help='file参数类型不正确或缺失')
        
        kwargs = parser.parse_args()
        kwargs = commons.put_remove_none(**kwargs)
        kwargs['file'] = kwargs['file'].encode('utf-8')

        kwargs['file_id'] = file_id

        res = FileController.update(**kwargs)

        return jsonify(code=res['code'], message=res['message'], data=res['data'])


# 新增实验信息
class FileAddResource(Resource):
    @classmethod
    @TokenRequire
    def post(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('student_id', location='form', required=True, help='student_id参数类型不正确或缺失')
        parser.add_argument('experiment_id', location='form', required=True, help='experiment_id参数类型不正确或缺失')
        try:
            data = parser.parse_args()
            data = commons.put_remove_none(**data)
            res = FileService.add(**data)
            if res.get("code") != RET.OK:
                logger.error(res.get("data").get("error"))
                return jsonify({
                    "code": res.get("code"),
                    "error": res.get("data").get("error"),
                    "message": "新增实验信息失败",
                })
            logger.info(f"user {res.get('data').get('OrderID')} add success")
            return jsonify({
                "code": RET.OK,
                "message": "新增实验信息成功",
                "data": res,
            })
        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))
        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))
